<template>
  <div>
    <el-upload
      :action="url"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="handleUploadFail"
      :on-success="handleUploadSuccess"
      :on-exceed="handleExceed"
      :file-list="imgUrl && imgUrl !== '' ? [{name: 'test', url: this.buildUri(imgUrl)}] : []"
      :with-credentials="true"
      :headers="headersData"
      :limit="1"
      name="files"
      :class="{hide: imgUrl}"
      list-type="picture-card">
      <el-button size="small" v-if="!imgUrl" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过5MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible"
               title="预览图片"
               :append-to-body="true">
      <img width="100%" height="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<style scoped>
</style>

<script>
import {getToken} from '@/utils/LocalDataUtil'
import config from '@/config/index'
export default {
  model: {
    prop: 'imgUrl',
    event: 'updateImgUrl'
  },
  props: {
    imgUrl: String,
    isBtn: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      fileList: [],
      headersData: {},
      url: '',
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  components: {},
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.url = config.serverUrl() + '/image/'
      this.headersData.token = getToken()
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    handleRemove (file, fileList) {
      this.fileList = []
      this.$emit('updateImgUrl', '')
    },
    // 上传图片后点击 + 号预览当前图片
    handlePreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleUploadSuccess (response, file, fileList) {
      if (response && response.code === '200' && response.data) {
        let imagePath = response.data[0] + ''
        // console.log(imagePath)
        let imageUri = this.buildUri(imagePath)
        let fileObj = {name: 'test', url: imageUri}
        this.fileList.push(fileObj)
        this.$emit('updateImgUrl', imagePath)
      } else {
        let message = `上传失败，原因：` + response.message
        this.$message.error(message)
      }
    },
    handleUploadFail (err, file, fileList) {
      console.log(err)
      console.log(file)
      console.log(fileList)
    },
    handleExceed (files, fileList) {
      this.$message.error('只能上传一个图片!')
    },
    clearFileList () { // 初始化fileList
      this.fileList = []
    },
    buildUri (path) {
      this.url = config.serverUrl() + '/image/'
      if (path && path !== '') {
        return this.url + path
      }
      return null
    }
  }
}
</script>
<style scoped>
.hide >>> .el-upload--picture-card {
    display: none;
}
</style>
